//
// GPSMapEdit
// (c) Konstantin Galichsky (kg@geopainting.com), 2002-2007
// Modified by Michael Sotin (m.u.s@mail.ru), 2004
//
// Dialog procedure helper enabling hyperlinks.
//

# include "StdAfx.h"
# include "Resource.h"
# include "LinkDlg.h"
# include "ParseHelpers.h"
# include "Globals.h"

static HFONT   g_hFont    = NULL;
static HCURSOR g_hcurHand = NULL;

static
bool IsURLWindow (HWND _hWnd) {
	if (_hWnd == NULL)
		return false;

	char strClass [10];
	::GetClassName (_hWnd, strClass, sizeof (strClass) - 1);
	strClass [sizeof (strClass) - 1] = '\0';

	if (::stricmp (strClass, "STATIC") != 0)
		return false;

	char strText [10];
	::GetWindowText (_hWnd, strText, sizeof (strText) - 1);
	strText [sizeof (strText) - 1] = '\0';

//	::UrlIs (strText, URLIS_URL)
	if (
		HasPrefix (strText, strText + sizeof (strText), "http:",   5) ||
		HasPrefix (strText, strText + sizeof (strText), "ftp:",    4) ||
		HasPrefix (strText, strText + sizeof (strText), "mailto:", 7)
	)
		return true;

	return false;
}

static
void _InitLinkDlg () {
	if (g_hFont == NULL) {
		// Prepare font for Web link (underlined).
		LOGFONT lf;
		::GetObject ((HFONT) ::GetStockObject (DEFAULT_GUI_FONT), sizeof (lf), & lf);
		lf.lfUnderline = TRUE;
		g_hFont = ::CreateFontIndirect (& lf);

		// Prepare hand cursor.
		g_hcurHand = ::LoadCursor (NULL, MAKEINTRESOURCE (IDC_HAND));
		if (g_hcurHand == NULL)
			g_hcurHand = ::LoadCursor (g_hInst, MAKEINTRESOURCE (IDC_CursorHand));
	}
}

INT_PTR LinkDlgProc (HWND _hWnd, UINT _uMsg, WPARAM _wParam, LPARAM _lParam) {
	switch (_uMsg) {
		case WM_CTLCOLORSTATIC:
			if (IsURLWindow (reinterpret_cast<HWND> (_lParam))) {
				_InitLinkDlg ();

				// Before repainting Web link.
				const HDC hdc = reinterpret_cast<HDC> (_wParam);
				::SetTextColor (hdc, c_colBlue);//::GetSysColor (COLOR_HOTLIGHT));
				::SelectObject (hdc, g_hFont);
				::SetBkMode (hdc, TRANSPARENT);
				return reinterpret_cast<LRESULT> (::GetSysColorBrush (COLOR_3DFACE));
			}
			return FALSE;

		case WM_SETCURSOR: {
			POINT pt;
			::GetCursorPos (& pt);
			if (IsURLWindow (::WindowFromPoint (pt))) {
				_InitLinkDlg ();

				// On moving cursor over URL.
                ::SetCursor (g_hcurHand);
				::SetWindowLong (_hWnd, DWL_MSGRESULT, TRUE);
				return TRUE;
			} else
				return FALSE;
		}

		case WM_COMMAND: {
			const HWND hCtl = reinterpret_cast<HWND> (_lParam);
			if (IsURLWindow (hCtl) && HIWORD (_wParam) == STN_CLICKED) {
				// On click to URL.
				char strWebLink [256];
				::GetWindowText (hCtl, strWebLink, sizeof (strWebLink)/sizeof (strWebLink [0]));
				::ShellExecute (_hWnd, NULL, strWebLink, NULL, NULL, SW_SHOWNORMAL);
			}
			return FALSE;
		}
	}

	return FALSE;
}
